package fr.cpe.dp.projet2.factory;

import fr.cpe.dp.projet2.utils.Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 *
 * @author Benoit
 */
public class GenericFactory<T> {
    private String classPackage;

    public GenericFactory(String classPackage) {
        this.classPackage = classPackage;
    }
    
    public T createObject(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        Class<?> objectClass = Class.forName(classPackage + "." + type);
        return (T) objectClass.newInstance();
    }
    
    public T createObject(String type, List<Object> parameters) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        Class<?> objectClass = Class.forName(classPackage + "." +type);

        Class<?>[] parametersType = new Class<?>[parameters.size()];
        Object[] parametersValue = new Object[parameters.size()];
        parametersValue = parameters.toArray(parametersValue);

        int i=0;
        for(Object parameter: parameters) {
            parametersType[i++] = parameter.getClass();
        }

        Constructor<?> constructor = Reflection.getPossibleConstructor(objectClass,parametersType);
        if(constructor == null) {
            throw new NoSuchMethodException("Aucun constructeur ne correspond aux arguments fournis");
        }
        return (T) constructor.newInstance(parametersValue);
    }
}
